<?php

namespace app\stock\controller\business;

use think\Controller;

class Visit extends Controller
{
  public function _initialize()
  {
    parent::_initialize();
    $this->AdminModel = model('Admin');
    $this->BusinessModel = model('Business.Business');
    $this->VisitModel = model('Business.Visit');
  }

  public function index()
  {
    // $data = $this->VisitModel->with(['business' => function ($query) {
    //     $query->field('id,nickname');
    // }])->order('createtime DESC')->select();
    $data = $this->VisitModel->with(['business'])->order('createtime DESC')->select();

    $this->success('', '', $data);
  }


  public function add()
  {
    $adminid = $this->request->param('adminid', 0, 'trim');

    $busid = $this->request->param('busid', 0, 'trim');

    $content = $this->request->param('content', '', 'trim');

    $admininfo = $this->AdminModel->find($adminid);

    if (!$admininfo) {
      $this->error('管理员不存在');
    }

    $businessinfo = $this->BusinessModel->find($busid);

    if (!$businessinfo) {
      $this->success('当前用户不存在');
    }

    $data = [
      'content' => $content,
      'busid' => $busid,
      'adminid' => $adminid
    ];

    // 校验器
    $result = $this->VisitModel->save($data);

    if ($result) {
      $this->success('添加成功');
    } else {
      $this->error('添加失败');
    }
  }

  // 删除
  public function del()
  {
    $visitid = $this->request->param('visitid', 0, 'trim');

    $info = $this->VisitModel->find($visitid);

    if (!$info) {
      $this->error('回访内容不存在');
    }

    $result = $this->VisitModel->destroy($visitid);

    if ($result === false) {
      $this->error('删除失败');
    } else {
      $this->success('删除成功');
    }
  }

  public function info()
  {
    $visitid = $this->request->param('visitid', 0, 'trim');

    $info = $this->VisitModel->with(['business'])->find($visitid);

    if (!$info) {
      $this->error('回访内容不存在');
    }

    $this->success('', '', $info);
  }

  public function edit()
  {
    $adminid = $this->request->param('adminid', 0, 'trim');

    $busid = $this->request->param('busid', 0, 'trim');

    $content = $this->request->param('content', '', 'trim');

    $visitid = $this->request->param('visitid', 0, 'trim');

    $admininfo = $this->AdminModel->find($adminid);

    if (!$admininfo) {
      $this->error('管理员不存在');
    }

    $businessinfo = $this->BusinessModel->find($busid);

    if (!$businessinfo) {
      $this->success('当前用户不存在');
    }

    $info = $this->VisitModel->find($visitid);

    if (!$info) {
      $this->error('回访内容不存在');
    }


    $data = [
      'id' => $visitid,
      'content' => $content,
      'busid' => $busid
    ];

    // 校验器
    $result = $this->VisitModel->isUpdate()->save($data);

    if ($result) {
      $this->success('编辑成功');
    } else {
      $this->error('编辑失败');
    }
  }
}
